

const fs = require('fs');
const path = require('path');
const serialize = require('serialize-javascript');

const Controller = require('egg').Controller;

function parseIndexHtml(template) {
  const contentMarker = '<!-- INIT_STATE -->';
  const i = template.indexOf(contentMarker);
  return {
    head: template.slice(0, i),
    tail: template.slice(i + contentMarker.length),
  };
}

class HomeController extends Controller {
  async index() {
    this.ctx.body = 'hi, egg';
  }

  async login() {
    this.ctx.session = null;
    await this.render();
  }

  async render() {
    const { ctx } = this;
    const htmlFile = await this.getTpl();
    const indexHTML = parseIndexHtml(htmlFile);
    const initState = {
      common: {
        csrfToken: ctx.csrf,
      },
    };
    ctx.type = 'html';
    ctx.body = `
    ${indexHTML.head.replace(/\{cspNonce\}/g, ctx.cspNonce)}
    <script>
      window.INIT_STATE = JSON.parse('${serialize(initState, { isJSON: true })}')
    </script>
    ${indexHTML.tail.replace(/\{cspNonce\}/g, ctx.cspNonce)}
  `;
  }

  async getTpl() {
    const { app } = this;
    let htmlFile;
    if (app.config.env === 'local') {
      const result = await app.curl('http://localhost:9001/webpack/index.html', {
        dataType: 'text',
      });
      htmlFile = result.data;
    } else {
      htmlFile = await (new Promise(((resolve, reject) => {
        fs.readFile(path.resolve(__dirname, '../public/index.html'), 'utf8', (err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data);
          }
        });
      })));
    }
    return htmlFile;
  }
}

module.exports = HomeController;
